// 修改菜单创建函数
function createContextMenu() {
  chrome.storage.local.get(['tools', 'useMenuBar'], ({ tools, useMenuBar }) => {
    if (!useMenuBar) {
      chrome.contextMenus.removeAll()
    } else {
      chrome.contextMenus.removeAll(() => {
        chrome.contextMenus.create({
          id: 'progress',
          title: 'progress',
          contexts: ['all'],
        })
        tools
          .filter((tool) => tool.menuEnabled)
          .forEach((tool) => {
            chrome.contextMenus.create({
              parentId: 'progress',
              id: tool.path,
              title: tool.name,
              contexts: ['all'],
            })
          })
      })
    }
  })
}

// 监听所有相关变化
chrome.storage.local.onChanged.addListener((changes) => {
  if (changes.tools || changes.useMenuBar) {
    createContextMenu()
  }
})

// 监听菜单点击事件
chrome.contextMenus.onClicked.addListener((info) => {
  let url = info.menuItemId
  if (info.menuItemId.indexOf('http') < 0) {
    url = chrome.runtime.getURL(`apps/${info.menuItemId}`)
  }
  chrome.tabs.create({ url })
})

// 初始化存储
chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.local.get(['tools', 'useMenuBar'], ({ tools }) => {
    if (!tools) {
      const defaultTools = [
        {
          key: 'draw',
          name: '白板',
          path: 'draw/index.html',
          menuEnabled: false,
        },
        {
          key: 'mind',
          name: '思维导图',
          path: 'mind/index.html',
          menuEnabled: false,
        },
        {
          key: 'note',
          name: '笔记',
          path: 'http://progress123.online/#/home',
          menuEnabled: false,
        },
      ]
      chrome.storage.local.set({ tools: defaultTools })
    }
    createContextMenu()
  })
})

